package fm.dongman.modellib.source

import fm.dongman.animefm.contractlib.BaseDataSource
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.ComicTimeContract
import fm.dongman.modellib.RemoteHelper
import fm.dongman.modellib.StaticArea.StaticUrl
import fm.dongman.modellib.model.ComicModel
import fm.dongman.modellib.remote.RemoteOperationHelper
import org.json.JSONObject
import java.util.ArrayList

/**
 * 每周时间表数据
 * Created by shize on 2017/10/31.
 */

class ComicTimeRepository private constructor() : ComicTimeContract.IComicTimeDataSource {
    private val mWeekdays: List<Map<String, String>> = listOf(mapOf(Pair("Monday", "周一")),
            mapOf(Pair("Tuesday", "周二")), mapOf(Pair("Wednesday", "周三")), mapOf(Pair("Thursday", "周四"))
            , mapOf(Pair("Friday", "周五")), mapOf(Pair("Saturday", "周六")), mapOf(Pair("Sunday", "周日")))

    override fun getWeekDayComics(weekday: String, callback: BaseDataSource.LoadSourceCallback<List<IModel.IComicModel>>) {
        val jsonObj = RemoteHelper.instance.parseGetUrl(StaticUrl.COMIC_REMOTE + "season=0&is_season=0&is_timeline=1&tucao_num=0&recent_num=0")
        if (jsonObj == null) {
            callback.onDataLoadFiled()
            return
        }
        callback.onDataLoaded(downComicTime(weekday, jsonObj))
    }

    override fun getData(callback: BaseDataSource.LoadSourceCallback<List<Map<String, String>>>) {
        callback.onDataLoaded(mWeekdays)
    }

    /**
     * 解析时间表
     */
    private fun downComicTime(weekday: String, jsonObject: JSONObject): List<IModel.IComicModel> {
        val models = ArrayList<IModel.IComicModel>()
        try {
            val jsonArray = jsonObject.getJSONObject("data").getJSONObject(TIME_SCHEDULE).getJSONArray(weekday)
            (0 until jsonArray.length()).forEach {
                models.add(RemoteOperationHelper.getOperationHelper().parseComicModel(jsonArray.getJSONObject(it)))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return models
    }

    override fun saveData(dataModel: List<Map<String, String>>) {}

    override fun refreshData() {}

    override fun offLine() {}

    companion object {
        val TIME_SCHEDULE = "schedule"
        private var SINGLETON: ComicTimeRepository? = null

        val instance: ComicTimeRepository
            get() {
                if (SINGLETON == null) {
                    SINGLETON = ComicTimeRepository()
                }
                return SINGLETON!!
            }
    }
}
